package com.nf.health.app.inquiry.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.easeui.EaseConstant;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.global.PictureActivity;
import com.nf.health.app.inquiry.InquirySendHeartDialog;
import com.nf.health.app.inquiry.adapter.DetailDoctorListAdapter;
import com.nf.health.app.inquiry.adapter.DetailGridViewAdapter;
import com.nf.health.app.inquiry.bean.DoctorListClickBean;
import com.nf.health.app.inquiry.bean.InquiryDetailBean;
import com.nf.health.app.inquiry.docdetail.DocDetailActivity;
import com.nf.health.app.inquiry.docdetail.DocHomeOrderActivity;
import com.nf.health.app.inquiry.docdetail.DocPayConunselActivity;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.DialogHelp;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.ViewUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by hepann on 2016/9/23.
 * The only genius that is worth anything is the genius for hard work
 *
 * @author hepann
 * @Description 问诊详情类
 * @email he_pann@163.com
 */
public class InquiryDetailActivity extends BaseActivity {

    public static final String IS_COMPLET = "is_complet";
    public static final String INQUIRY_ID = "inquiryid";
    public static final String GET_DETAIL_INQUIRY = "get_detail_inquiry";
    public static final String UPDATE_READ_TYPE = "update_read_type";
    public static final String ATTENTION_DOCTOR = "attention_doctor";
    public static final String CANCEL_ATTENTION_DOCTOR = "cancel_attention_doctor";

    private static class MyHandler extends Handler {
        private final WeakReference<InquiryDetailActivity> mActivity;

        public MyHandler(InquiryDetailActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            InquiryDetailActivity activity = mActivity.get();
            if (activity != null) {
                if (msg.what == 1) {
                    activity.isViewshow = true;
                }
            }
        }
    }

    private final MyHandler mHandler = new MyHandler(this);

    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.tv_user_desc)
    TextView tvUserDesc;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.rl_base_info)
    RelativeLayout rlBaseInfo;
    @Bind(R.id.lv_doctor_list)
    ListView lvDoctorList;
    @Bind(R.id.tv_message)
    TextView tvMessage;
    @Bind(R.id.gv_images)
    GridView gvImages;
    @Bind(R.id.ll_detail_info)
    LinearLayout llDetailInfo;
    @Bind(R.id.tv_date_and_reply)
    TextView tvDateAndReply;
    @Bind(R.id.tv_inquiry_state)
    TextView tvInquiryState;
    @Bind(R.id.iv_arrow)
    ImageView ivArrow;

    private String inquiryId;
    private InquiryDetailBean mDetailBean;
    private DetailGridViewAdapter mGridViewAdapter;
    private DetailDoctorListAdapter mDoctorListAdapter;
    private String healthMoney;
    //标记是否是已完成问题
    private boolean isComplete;
    //标记是否正在显示view
    private boolean isViewshow = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_inquiry_detail);
        ButterKnife.bind(this);
        inquiryId = getIntent().getStringExtra(INQUIRY_ID);
        isComplete = getIntent().getBooleanExtra(IS_COMPLET, false);
        EventBus.getDefault().register(this);
        initView();
        initListener();
        initData(GET_DETAIL_INQUIRY);
    }


    private void initView() {
        ViewUtil.setText(this, R.id.titlebar_title_tv, "问诊详情");
        titlebarRightView.setImageResource(R.drawable.inquiry_question);
    }

    private void initListener() {
        titlebarRightView.setOnClickListener(this);
        rlBaseInfo.setOnClickListener(this);
        //点击显示大图
        gvImages.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mDetailBean.getInquiry().getContentBean().getImages().size() > 0) {
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("imgUrls", mDetailBean.getInquiry().getContentBean().getImages());
                    bundle.putInt("position", position);
                    bundle.putInt("type", PictureActivity.TYPE_NET_IMG);
                    ActivityUtils.showActivity(InquiryDetailActivity.this, PictureActivity.class, bundle);
                }
            }
        });
        //listView点击监听
        lvDoctorList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
//                if (scrollState == SCROLL_STATE_TOUCH_SCROLL && getScrollY()==0){
//                    llDetailInfo.setVisibility(View.VISIBLE);
//                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                shadeLlDetailInfo();
            }
        });
    }

    //根据lv滚动隐藏问诊详情
    private void shadeLlDetailInfo() {
        int scrollHeight = getScrollY();
//        Log.e("高度", scrollHeight + "");
        if (scrollHeight > 90 && isViewshow) {
            isViewshow = false;
            llDetailInfo.setVisibility(View.GONE);
        }
    }

    private void initData(String flag) {
        provider.getInquiryById(inquiryId, flag);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (GET_DETAIL_INQUIRY.equals(actionName)) {
            mDetailBean = (InquiryDetailBean) object;
            //根据请求结果设置ui
            if (mDetailBean != null) {
                initViewByBean();
            }
        } else if (UPDATE_READ_TYPE.equals(actionName)) {
//            showToast("修改已读状态成功");
//            initData(GET_DETAIL_INQUIRY);
            mDetailBean.getDoctorlist().get(position).setReadtype("-1");
            mDoctorListAdapter.setInquiryDetailBean(mDetailBean);
        } else if (ATTENTION_DOCTOR.equals(actionName)) {
            showToast("关注医生成功");
            initData(GET_DETAIL_INQUIRY);
        } else if (CANCEL_ATTENTION_DOCTOR.equals(actionName)) {
            showToast("取消关注医生成功");
            initData(GET_DETAIL_INQUIRY);
        }
    }

    /**
     * 根据bean设置ui
     */
    private void initViewByBean() {
        //基本信息行
        String desc = mDetailBean.getInquiry().getUserdesc();
        if(TextUtils.isEmpty(desc)){
            desc = "";
        }else if(desc.contains(",")){
            desc = desc.replace(","," ");
        }
        tvUserDesc.setText(desc);
        tvDate.setText(DateUtil.date2String(mDetailBean.getInquiry().getCreatetime(), "yyyy.MM.dd"));
        //问题详情
        String message = mDetailBean.getInquiry().getContentBean().getMessage();
        tvMessage.setText(message);
        //图片
        if (mGridViewAdapter == null) {
            mGridViewAdapter = new DetailGridViewAdapter(mDetailBean, this);
            gvImages.setAdapter(mGridViewAdapter);
            lvDoctorList.setAdapter(mGridViewAdapter);
        }
        mGridViewAdapter.notifyDataSetChanged();
        if (mDetailBean.getInquiry().getContentBean().getImages().size() == 0) {
            gvImages.setVisibility(View.GONE);
        }

        //问题时间,追问条数
        if (!isComplete) {
            tvInquiryState.setVisibility(View.INVISIBLE);
            String hour = DateUtil.formatDuring(System.currentTimeMillis() - mDetailBean.getInquiry().getCreatetime());
            tvDateAndReply.setText(hour + "小时/" + mDetailBean.getInquiry().getUserreplynum() + "条追问后");
        } else {
            tvInquiryState.setVisibility(View.VISIBLE);
            tvDateAndReply.setVisibility(View.INVISIBLE);
        }
        //医生列表
        if (mDoctorListAdapter == null) {
            mDoctorListAdapter = new DetailDoctorListAdapter(mDetailBean, this);
            lvDoctorList.setAdapter(mDoctorListAdapter);
        }
        mDoctorListAdapter.setInquiryDetailBean(mDetailBean);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_view:
                DialogHelp.showH5Dialog(this, Constants.H5_TIP_SERVICE_TO_EXPLAIN);
                break;
            case R.id.rl_base_info:
                if (llDetailInfo.getVisibility() == View.VISIBLE) {
                    llDetailInfo.setVisibility(View.GONE);
                    ivArrow.setBackgroundResource(R.drawable.inquiey_detail_arrowdown);
                } else if (llDetailInfo.getVisibility() == View.GONE) {
                    llDetailInfo.setVisibility(View.VISIBLE);
                    ivArrow.setBackgroundResource(R.drawable.inquiey_detail_arrowup);
                    //延时发送,处理点击展开时页面空白问题
                    mHandler.sendEmptyMessageDelayed(1, 1000);
                }
                break;
            default:
                break;
        }
    }


    /**
     * 获得listview的滚动的距离(不在页面显示的Y轴长度)
     *
     * @return
     */
    public int getScrollY() {
        View c = lvDoctorList.getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = lvDoctorList.getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight();
    }

    /**
     * 处理医生列表的点击事件,头像,关注,心意等
     *
     * @param bean
     */
    int position;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleClickAction(DoctorListClickBean bean) {
        int type = bean.getType();
        position = bean.getPosition();
        InquiryDetailBean.DoctorlistBean doctorBean = mDetailBean.getDoctorlist().get(position);
        LogUtil.e("点击了" + type + position);
        if (DoctorListClickBean.DOCTOR_HIMG == type) {
            //头像
            Bundle docDetailBundle = new Bundle();
            docDetailBundle.putString(DocDetailActivity.DOCTORID, doctorBean.getDoctorid());
            ActivityUtils.showActivity(InquiryDetailActivity.this, DocDetailActivity.class, docDetailBundle);

        } else if (DoctorListClickBean.ATTENTION == type) {
            //关注(取消关注)医生
            if ("0".equals(doctorBean.getAttention())) {
                provider.requestFoucsDoctor(doctorBean.getDoctorid(), ATTENTION_DOCTOR);
            } else if ("1".equals(doctorBean.getAttention())) {
                provider.requestCancleFoucsDoctor(doctorBean.getDoctorid(), CANCEL_ATTENTION_DOCTOR);
            }
        } else if (DoctorListClickBean.COMMENT == type) {
            //评价
            Bundle commentBundle = new Bundle();
            commentBundle.putString(AssessActivity.INQUIRY_ID, inquiryId);
            commentBundle.putString(AssessActivity.DOCTOR_ID, doctorBean.getDoctorid());
            commentBundle.putSerializable(AssessActivity.DOCTOR_LIST_BEAN, doctorBean);
            ActivityUtils.showActivity(InquiryDetailActivity.this, AssessActivity.class, commentBundle);
        } else if (DoctorListClickBean.REPLY_DOCTOR == type) {
            //追问
            Bundle consultBundle = new Bundle();
            consultBundle.putBoolean(InquiryChatActivity.IS_COMPLET, false);
            consultBundle.putString(InquiryDetailActivity.INQUIRY_ID, inquiryId);
            consultBundle.putString(EaseConstant.EXTRA_USER_ID, doctorBean.getDoctorid());
            consultBundle.putSerializable(InquiryChatActivity.DOCTOR_LIST_BEAN, doctorBean);
            ActivityUtils.showActivity(InquiryDetailActivity.this, InquiryChatActivity.class, consultBundle);
        } else if (DoctorListClickBean.GIFT == type) {
            // 送心意
            InquirySendHeartDialog dialog = new InquirySendHeartDialog(this, doctorBean.getNick(), doctorBean.getDoctorid());
            dialog.show();
        } else if (DoctorListClickBean.CONSULT == type) {
            //咨询
            if ("2".equals(doctorBean.getConsult())) {
                Bundle docDetailBundle = new Bundle();
                docDetailBundle.putString(Constants.DOCTOR_ID, doctorBean.getDoctorid());
                ActivityUtils.showActivity(this, DocPayConunselActivity.class, docDetailBundle);

            } else if ("1".equals(doctorBean.getConsult())) {
                showToast("未开启");
            } else {
                showToast("未开启");
            }
        } else if (DoctorListClickBean.FAMILY_SERVICE == type) {
            //家庭服务 0 未开启 1 已开启
            if ("2".equals(doctorBean.getFamily())) {
                Bundle docDetailBundle2 = new Bundle();
                docDetailBundle2.putString(Constants.DOCTOR_ID, doctorBean.getDoctorid());
                ActivityUtils.showActivity(this, DocHomeOrderActivity.class, docDetailBundle2);

            } else if ("1".equals(doctorBean.getFamily())) {
                showToast("未开启");
            } else {
                showToast("未开启");
            }

        } else if (DoctorListClickBean.HEALTH_MANAGE == type) {
            //健康管理
            if ("2".equals(doctorBean.getSound())) {
                showToast("已开启");
            } else if ("1".equals(doctorBean.getSound())) {
                showToast("未开启");
            } else {
                showToast("未开启");
            }

        } else if (DoctorListClickBean.READ_REPLY == type) {
            //读取最新信息后更改已读状态
            provider.updateReadtype(doctorBean.getDoctorid(), mDetailBean.getInquiry().getId(), "-1", UPDATE_READ_TYPE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData(GET_DETAIL_INQUIRY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
